package com.eoi.docs.util;

import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;

/**
 * Created by tao.zeng on 2022/11/7.
 */
public class DocsUtils {

    /**
     * 输出Markdown到单文件
     *
     * @param url
     * @throws MalformedURLException
     */
    public static void markdown(String fileName, String url, String output) throws MalformedURLException {
        build(MarkupLanguage.MARKDOWN, fileName, url, output);
    }

    public static void confluence(String fileName, String url, String output) throws MalformedURLException {
        build(MarkupLanguage.CONFLUENCE_MARKUP, fileName, url, output);
    }


    public static void document(String fileName, String url, String output) throws MalformedURLException {
        build(MarkupLanguage.ASCIIDOC, fileName, url, output);
    }


    /**
     * 构建文件
     *
     * @param markupLanguage
     * @param fileName
     * @param url
     * @throws MalformedURLException
     */
    private static void build(MarkupLanguage markupLanguage, String fileName, String url, String output) throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(markupLanguage)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        String filePath = StringUtils.isEmpty(output) ?
                String.join(File.separator, System.getProperty("user.dir"), "asciidoc", "docs", fileName) :
                String.join(File.separator, output, fileName);

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toPath(Paths.get(filePath));
    }
}
